// Copyright (C) 2024 wwhai
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

package rhilexg1

import (
	"context"
	"fmt"
	"html/template"
	"net"
	"os"
	"os/exec"
	"time"
)

// getEthList returns a list of Ethernet (wired) interfaces.
func getEthList() ([]net.Interface, error) {
	ifaces, err := net.Interfaces()
	if err != nil {
		return nil, err
	}
	var ethIfaces []net.Interface
	for _, iface := range ifaces {
		if isWirelessInterface(iface.Name) {
			continue
		}
		if iface.Name == "lo" {
			continue
		}
		ethIfaces = append(ethIfaces, iface)
	}

	return ethIfaces, nil
}

type NetworkInterfaceConfig struct {
	Interface   string
	Address     string
	Netmask     string
	Gateway     string
	DHCPEnabled bool
}

/**
 * 配置网络
 *
 */
func SetEthernet(configs []NetworkInterfaceConfig) error {
	for _, config := range configs {
		filePath := fmt.Sprintf("/etc/network/interfaces.d/%s.conf", config.Interface)
		// filePath := fmt.Sprintf("./data/%s.conf", config.Interface)
		if err := writeInterfaceConfig(config, filePath); err != nil {
			fmt.Printf("Error writing config for %s: %v\n", config.Interface, err)
		} else {
			fmt.Printf("Config written for %s to %s\n", config.Interface, filePath)
		}
	}
	restartNetwork()
	return nil
}

const configFileTemplate = `#
# GENERATED BY RHILEX, DON'T MODIFY THIS CONFIG!!!
#

auto lo
iface lo inet loopback

auto {{.Interface}}
iface {{.Interface}} inet {{if .DHCPEnabled}}dhcp{{else}}static{{end}}
{{if not .DHCPEnabled}}
    address {{.Address}}
    netmask {{.Netmask}}
    gateway {{.Gateway}}
{{end}}`

func writeInterfaceConfig(config NetworkInterfaceConfig, filePath string) error {
	// 解析模板
	tmpl, err := template.New("config").Parse(configFileTemplate)
	if err != nil {
		return err
	}
	file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
	if err != nil {
		return err
	}
	defer file.Close()
	return tmpl.Execute(file, config)
}
func restartNetwork() error {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	cmd := exec.CommandContext(ctx, "sh", "-c", `service networking restart`)
	output, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf(err.Error() + ":" + string(output))
	}
	return nil
}
